<template>
  <div class="billing-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>计费管理</span>
          <el-button type="primary" @click="showGenerateBillDialog">
            生成账单
          </el-button>
        </div>
      </template>

      <!-- 查询条件 -->
      <el-form :model="queryForm" :inline="true" class="query-form">
        <el-form-item label="客户">
          <el-select v-model="queryForm.customerId" placeholder="选择客户" clearable>
            <el-option
              v-for="customer in customers"
              :key="customer.id"
              :label="customer.name"
              :value="customer.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="计费周期">
          <el-date-picker
            v-model="queryForm.billingPeriod"
            type="month"
            placeholder="选择计费周期"
            format="YYYY-MM"
            value-format="YYYY-MM"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadBillingData">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 设备计费汇总表格 -->
      <div class="table-container">
        <el-table 
          :data="billingData" 
          border 
          style="width: 100%" 
          v-loading="loading"
          :max-height="tableMaxHeight"
        >
          <el-table-column prop="deviceId" label="设备ID" width="80" />
          <el-table-column prop="serialNo" label="设备序列号" width="150" />
          <el-table-column prop="model" label="设备型号" width="120" />
          <el-table-column prop="areaName" label="所属区域" width="120" />
          <el-table-column prop="siteName" label="所属站点" width="120" />
          <el-table-column prop="customerName" label="客户" width="120" />
          <el-table-column prop="currentMeterReading" label="当前读数" width="100" />
          <el-table-column prop="lastMeterReading" label="上次读数" width="100" />
          <el-table-column prop="usageAmount" label="用水量(吨)" width="100" />
          <el-table-column label="预估费用(元)" width="120">
            <template #default="{ row }">
              <span class="estimated-cost" :class="{ 'zero-cost': getEstimatedCost(row) === 0 }">
                {{ getEstimatedCost(row).toFixed(2) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="billingPeriod" label="计费周期" width="100" />
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button size="small" type="primary" @click="updateMeterReading(row)">
                更新读数
              </el-button>
              <el-button size="small" type="success" @click="configureTieredPricing(row)">
                阶梯水费
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 生成账单对话框 -->
    <el-dialog 
      v-model="generateBillDialogVisible" 
      title="生成账单" 
      :width="dialogWidth"
      :close-on-click-modal="false"
    >
      <el-form :model="generateBillForm" :rules="generateBillRules" ref="generateBillFormRef">
                 <el-form-item label="客户" prop="customerId">
           <el-select v-model="generateBillForm.customerId" placeholder="选择客户" clearable>
             <el-option
               v-for="customer in customers"
               :key="customer.id"
               :label="customer.name"
               :value="customer.id"
             />
           </el-select>
         </el-form-item>
         <el-form-item label="计费周期" prop="billingPeriod">
           <el-date-picker
             v-model="generateBillForm.billingPeriod"
             type="month"
             placeholder="选择计费周期"
             format="YYYY-MM"
             value-format="YYYY-MM"
             clearable
           />
         </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="generateBillDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="generateBill" :loading="generating">
          生成账单
        </el-button>
      </template>
    </el-dialog>

    <!-- 更新抄表读数对话框 -->
    <el-dialog 
      v-model="meterReadingDialogVisible" 
      title="更新抄表读数" 
      :width="dialogWidth"
      :close-on-click-modal="false"
    >
      <el-form :model="meterReadingForm" :rules="meterReadingRules" ref="meterReadingFormRef">
        <el-form-item label="设备序列号">
          <span>{{ selectedDevice?.serialNo }}</span>
        </el-form-item>
        <el-form-item label="当前读数" prop="currentReading">
          <el-input-number
            v-model="meterReadingForm.currentReading"
            :min="0"
            :precision="2"
            placeholder="请输入当前抄表读数"
          />
        </el-form-item>
        <el-form-item label="计费周期" prop="billingPeriod">
          <el-date-picker
            v-model="meterReadingForm.billingPeriod"
            type="month"
            placeholder="选择计费周期"
            format="YYYY-MM"
            value-format="YYYY-MM"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="meterReadingDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitMeterReading" :loading="updating">
          更新读数
        </el-button>
      </template>
    </el-dialog>

    <!-- 阶梯水费配置对话框 -->
    <el-dialog 
      v-model="waterPriceDialogVisible" 
      title="阶梯水费配置" 
      :width="largeDialogWidth"
      :close-on-click-modal="false"
    >
      <div class="tier-config-container">
        <div class="area-info">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="区域名称">{{ selectedArea?.name }}</el-descriptions-item>
            <el-descriptions-item label="区域ID">{{ selectedArea?.id }}</el-descriptions-item>
          </el-descriptions>
        </div>
        
        <div class="tier-list">
          <div class="tier-header">
            <h4>阶梯配置</h4>
            <el-button type="primary" size="small" @click="addTier">
              <el-icon><Plus /></el-icon>添加阶梯
            </el-button>
          </div>
          
          <div class="tier-table-container">
            <el-table :data="tierList" border style="width: 100%">
              <el-table-column prop="tierName" label="阶梯名称" min-width="100">
                <template #default="{ row, $index }">
                  <el-input v-model="row.tierName" placeholder="如：第一阶梯" />
                </template>
              </el-table-column>
              <el-table-column prop="minUsage" label="最小用量(吨)" min-width="120">
                <template #default="{ row, $index }">
                  <el-input-number 
                    v-model="row.minUsage" 
                    :min="0" 
                    :precision="2" 
                    :disabled="$index === 0"
                    placeholder="最小用量"
                    controls-position="right"
                  />
                </template>
              </el-table-column>
                             <el-table-column prop="maxUsage" label="最大用量(吨)" min-width="120">
                 <template #default="{ row, $index }">
                   <el-input-number 
                     v-model="row.maxUsage" 
                     :min="0" 
                     :precision="2"
                     placeholder="留空表示无上限"
                     controls-position="right"
                     @change="() => validateTierConfig(row, $index)"
                   />
                 </template>
               </el-table-column>
               <el-table-column prop="unitPrice" label="单价(元/吨)" min-width="120">
                 <template #default="{ row, $index }">
                   <el-input-number 
                     v-model="row.unitPrice" 
                     :min="0" 
                     :precision="2"
                     placeholder="单价"
                     controls-position="right"
                     @change="() => validateTierConfig(row, $index)"
                   />
                 </template>
               </el-table-column>
              <el-table-column prop="remark" label="备注" min-width="150">
                <template #default="{ row }">
                  <el-input v-model="row.remark" placeholder="备注信息" />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80" fixed="right">
                <template #default="{ $index }">
                  <el-button 
                    type="danger" 
                    size="small" 
                    @click="removeTier($index)"
                    :disabled="tierList.length <= 1"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        
        <div class="preview-section">
          <h4>计费预览</h4>
          <el-form :inline="true" class="preview-form">
            <el-form-item label="测试用水量(吨)">
              <el-input-number 
                v-model="previewUsage" 
                :min="0" 
                :precision="2"
                @change="calculatePreview"
                controls-position="right"
              />
            </el-form-item>
            <el-form-item label="预估费用">
              <span class="preview-amount">¥{{ previewAmount.toFixed(2) }}</span>
            </el-form-item>
          </el-form>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="waterPriceDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitTierConfig" :loading="updating">
          保存配置
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { BillingAPI } from '@/api/system/billing.api'
import CustomerAPI from '@/api/system/customer.api'
import { getGlobalTiers, saveGlobalTiers, calculateGlobalTieredPrice } from '@/api/system/global-water-price-tier'


// 响应式数据
const queryForm = reactive({
  customerId: null,
  billingPeriod: null
})

const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const billingData = ref([])
const customers = ref([])
const generating = ref(false)
const updating = ref(false)
const loading = ref(false)

// 对话框相关
const generateBillDialogVisible = ref(false)
const meterReadingDialogVisible = ref(false)
const waterPriceDialogVisible = ref(false)

const generateBillForm = reactive({
  customerId: null,
  billingPeriod: null
})

const meterReadingForm = reactive({
  currentReading: null,
  billingPeriod: null
})



const selectedDevice = ref(null)
const selectedArea = ref(null)

// 阶梯水费配置相关
const tierList = ref([])
const previewUsage = ref(10)
const previewAmount = ref(0)

// 响应式对话框宽度
const dialogWidth = computed(() => {
  return window.innerWidth < 768 ? '90%' : '500px'
})

const largeDialogWidth = computed(() => {
  if (window.innerWidth < 480) {
    return '98%'
  } else if (window.innerWidth < 768) {
    return '95%'
  } else if (window.innerWidth < 1200) {
    return '90%'
  } else {
    return '80%'
  }
})

// 表格最大高度
const tableMaxHeight = computed(() => {
  return window.innerHeight - 400 // 预留空间给其他元素
})

// 通用阶梯水费计算函数 - 与后端逻辑保持一致
const calculateTieredCost = (usageAmount, tiers = null) => {
  if (usageAmount <= 0) {
    return 0
  }
  
  // 如果没有提供阶梯配置，使用默认阶梯
  if (!tiers || tiers.length === 0) {
    // 默认阶梯配置
    tiers = [
      { minUsage: 0, maxUsage: 10, unitPrice: 3.5 },
      { minUsage: 10, maxUsage: 50, unitPrice: 4.2 },
      { minUsage: 50, maxUsage: null, unitPrice: 5.0 }
    ]
  }
  
  let totalAmount = 0
  let remainingUsage = usageAmount
  
  // 按阶梯计算费用 - 与后端逻辑保持一致
  for (let i = 0; i < tiers.length; i++) {
    if (remainingUsage <= 0) {
      break
    }
    
    const tier = tiers[i]
    const minUsage = parseFloat(tier.minUsage) || 0
    const maxUsage = tier.maxUsage === null || tier.maxUsage === '' ? null : parseFloat(tier.maxUsage)
    const unitPrice = parseFloat(tier.unitPrice) || 0
    
    // 计算当前阶梯的可用用量
    let tierUsage
    if (maxUsage === null) {
      // 无上限阶梯
      tierUsage = remainingUsage
    } else {
      // 有上限阶梯
      const tierRange = maxUsage - minUsage
      tierUsage = remainingUsage > tierRange ? tierRange : remainingUsage
    }
    
    // 计算当前阶梯的费用
    if (tierUsage > 0) {
      const tierAmount = tierUsage * unitPrice
      totalAmount += tierAmount
      remainingUsage -= tierUsage
    }
  }
  
  return totalAmount
}

// 预估费用计算函数 - 使用阶梯水费计算
const getEstimatedCost = (row) => {
  // 优先使用后端返回的预估费用（后端已使用阶梯水费计算）
  if (row.estimatedCost !== undefined && row.estimatedCost !== null) {
    return parseFloat(row.estimatedCost)
  }
  
  // 如果后端没有返回预估费用，则前端计算
  const usageAmount = parseFloat(row.usageAmount) || 0
  
  // 使用通用阶梯水费计算函数
  const totalAmount = calculateTieredCost(usageAmount)
  
  // 调试信息
  console.log(`设备${row.deviceId}预估费用计算:`, {
    usageAmount,
    totalAmount,
    backendEstimatedCost: row.estimatedCost
  })
  
  return totalAmount
}

// 表单验证规则
const generateBillRules = {
  customerId: [
    { required: true, message: '请选择客户', trigger: 'change' }
  ],
  billingPeriod: [
    { required: true, message: '请选择计费周期', trigger: 'change' }
  ]
}

const meterReadingRules = {
  currentReading: [{ required: true, message: '请输入当前抄表读数', trigger: 'blur' }],
  billingPeriod: [{ required: true, message: '请选择计费周期', trigger: 'change' }]
}



const generateBillFormRef = ref()
const meterReadingFormRef = ref()


// 方法
const loadCustomers = async () => {
  try {
    const response = await CustomerAPI.getCustomerList()
    customers.value = response || []
  } catch (error) {
    console.error('加载客户列表失败:', error)
    ElMessage.error('加载客户列表失败')
  }
}

const loadBillingData = async () => {
  try {
    loading.value = true
    
    const params = {
      ...queryForm,
      currentPage: pagination.currentPage,
      pageSize: pagination.pageSize
    }
    
    const response = await BillingAPI.getDeviceBillingSummary(params)
    
    // 由于request.js的响应拦截器已经返回了data部分，所以response直接就是后端返回的result对象
    if (response) {
      billingData.value = response.records || []
      pagination.total = response.total || 0
      console.log('计费数据加载成功:', response)
      
      // 调试预估费用计算
      billingData.value.forEach(item => {
        console.log(`设备${item.deviceId}预估费用计算:`, {
          usageAmount: item.usageAmount,
  
          estimatedCost: getEstimatedCost(item)
        })
      })
    } else {
      ElMessage.error('获取数据失败')
    }
  } catch (error) {
    console.error('加载计费数据失败:', error)
    ElMessage.error('加载计费数据失败')
  } finally {
    loading.value = false
  }
}

const resetQuery = () => {
  Object.assign(queryForm, {
    customerId: null,
    billingPeriod: null
  })
  pagination.currentPage = 1
  loadBillingData()
}

const showGenerateBillDialog = () => {
  generateBillForm.customerId = null
  generateBillForm.billingPeriod = null
  generateBillDialogVisible.value = true
}

const generateBill = async () => {
  try {
    await generateBillFormRef.value.validate()
    
    // 添加调试信息
    console.log('生成账单参数:', generateBillForm)
    
    generating.value = true
    await BillingAPI.generateBillFromDevices(generateBillForm)
    
    ElMessage.success('账单生成成功')
    generateBillDialogVisible.value = false
    loadBillingData()
  } catch (error) {
    console.error('生成账单失败:', error)
    ElMessage.error('生成账单失败')
  } finally {
    generating.value = false
  }
}

const updateMeterReading = (row) => {
  selectedDevice.value = row
  meterReadingForm.currentReading = row.currentMeterReading
  meterReadingForm.billingPeriod = row.billingPeriod
  meterReadingDialogVisible.value = true
}

const submitMeterReading = async () => {
  try {
    await meterReadingFormRef.value.validate()
    
    // 添加调试信息
    console.log('更新抄表读数参数:', {
      deviceId: selectedDevice.value?.deviceId,
      currentReading: meterReadingForm.currentReading,
      billingPeriod: meterReadingForm.billingPeriod,
      selectedDevice: selectedDevice.value
    })
    
    updating.value = true
    await BillingAPI.updateDeviceMeterReading(
      selectedDevice.value.deviceId,
      meterReadingForm.currentReading,
      meterReadingForm.billingPeriod
    )
    
    ElMessage.success('抄表读数更新成功')
    meterReadingDialogVisible.value = false
    loadBillingData()
  } catch (error) {
    console.error('更新抄表读数失败:', error)
    ElMessage.error('更新失败')
  } finally {
    updating.value = false
  }
}

// 配置阶梯水费
const configureTieredPricing = async (row) => {
  try {
    // 获取区域信息
    const areaResponse = await BillingAPI.getAreaInfo(row.areaId)
    selectedArea.value = areaResponse
    
    // 加载现有的阶梯配置
    await loadTierConfig(row.areaId)
    
    waterPriceDialogVisible.value = true
  } catch (error) {
    console.error('获取区域信息失败:', error)
    ElMessage.error('获取区域信息失败')
  }
}

// 加载阶梯配置
const loadTierConfig = async (areaId) => {
  try {
    const response = await getGlobalTiers()
    if (response && response.data) {
      tierList.value = response.data
    } else {
      // 如果没有配置，创建默认配置
      tierList.value = [
        {
          tierName: '第一阶梯',
          minUsage: 0,
          maxUsage: 10,
          unitPrice: 3.5,
          remark: '基础用水量，单价较低'
        },
        {
          tierName: '第二阶梯',
          minUsage: 10,
          maxUsage: 50,
          unitPrice: 4.2,
          remark: '中等用水量，单价适中'
        },
        {
          tierName: '第三阶梯',
          minUsage: 50,
          maxUsage: null,
          unitPrice: 5.0,
          remark: '高用水量，单价较高'
        }
      ]
    }
    // 立即计算预览费用
    calculatePreview()
  } catch (error) {
    console.error('加载阶梯配置失败:', error)
    ElMessage.error('加载阶梯配置失败')
  }
}

// 添加阶梯
const addTier = () => {
  const newTier = {
    tierName: `第${tierList.value.length + 1}阶梯`,
    minUsage: 0,
    maxUsage: null,
    unitPrice: 3.5,
    remark: ''
  }
  tierList.value.push(newTier)
  // 重新计算预览
  calculatePreview()
}

// 删除阶梯
const removeTier = (index) => {
  ElMessageBox.confirm(
    '确定要删除这个阶梯吗？删除后无法恢复。',
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      tierList.value.splice(index, 1)
      // 重新排序
      tierList.value.forEach((tier, idx) => {
        tier.tierName = `第${idx + 1}阶梯`
      })
      // 重新计算预览
      calculatePreview()
      ElMessage.success('阶梯删除成功')
    })
    .catch(() => {
      // 用户取消删除
    })
}

// 计算预览费用
const calculatePreview = () => {
  if (!tierList.value.length || previewUsage.value <= 0) {
    previewAmount.value = 0
    return
  }
  
  try {
    const totalUsage = previewUsage.value
    console.log('开始计算阶梯费用，总用量:', totalUsage)
    
    // 使用通用阶梯水费计算函数
    const totalAmount = calculateTieredCost(totalUsage, tierList.value)
    
    previewAmount.value = totalAmount
    console.log('阶梯计费预览计算完成:', {
      usage: previewUsage.value,
      totalAmount: totalAmount
    })
  } catch (error) {
    console.error('计算预览费用失败:', error)
    previewAmount.value = 0
  }
}

// 提交阶梯配置
const submitTierConfig = async () => {
  if (!selectedArea.value) {
    ElMessage.error('请先选择区域')
    return
  }
  
  if (tierList.value.length === 0) {
    ElMessage.error('请至少配置一个阶梯')
    return
  }
  
  // 验证阶梯配置
  for (let i = 0; i < tierList.value.length; i++) {
    const tier = tierList.value[i]
    if (!tier.tierName || tier.unitPrice === null || tier.unitPrice <= 0) {
      ElMessage.error(`请完善第${i + 1}个阶梯的配置`)
      return
    }
    
    // 验证最大用量必须大于最小用量
    if (tier.maxUsage !== null && tier.maxUsage !== '' && tier.maxUsage !== '留空表示无上限') {
      if (parseFloat(tier.maxUsage) <= parseFloat(tier.minUsage)) {
        ElMessage.error(`第${i + 1}阶梯的最大用量必须大于最小用量`)
        return
      }
    }
    
    // 验证下一阶梯的水费应该比上一阶梯贵
    if (i > 0) {
      const prevTier = tierList.value[i - 1]
      if (parseFloat(tier.unitPrice) <= parseFloat(prevTier.unitPrice)) {
        ElMessage.error(`第${i + 1}阶梯的单价应该比第${i}阶梯的单价高`)
        return
      }
    }
    
    // 验证阶梯范围
    if (i > 0) {
      const prevTier = tierList.value[i - 1]
      if (tier.minUsage !== prevTier.maxUsage) {
        ElMessage.error(`第${i + 1}个阶梯的最小用量应该等于第${i}个阶梯的最大用量`)
        return
      }
    }
  }
  
  try {
    updating.value = true
    await saveGlobalTiers(tierList.value)
    ElMessage.success('阶梯水费配置保存成功')
    waterPriceDialogVisible.value = false
  } catch (error) {
    console.error('保存阶梯配置失败:', error)
    ElMessage.error('保存阶梯配置失败: ' + error.message)
  } finally {
    updating.value = false
  }
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  loadBillingData()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadBillingData()
}

// 验证阶梯配置
const validateTierConfig = (tier, index) => {
  // 验证最大用量必须大于最小用量
  if (tier.maxUsage !== null && tier.maxUsage !== '' && tier.maxUsage !== '留空表示无上限') {
    if (parseFloat(tier.maxUsage) <= parseFloat(tier.minUsage)) {
      ElMessage.warning(`第${index + 1}阶梯的最大用量必须大于最小用量`)
      return false
    }
  }
  
  // 验证下一阶梯的水费应该比上一阶梯贵
  if (index > 0) {
    const prevTier = tierList.value[index - 1]
    if (parseFloat(tier.unitPrice) <= parseFloat(prevTier.unitPrice)) {
      ElMessage.warning(`第${index + 1}阶梯的单价应该比第${index}阶梯的单价高`)
      return false
    }
  }
  
  return true
}

// 监听阶梯配置变化，自动重新计算预览
watch(tierList, () => {
  calculatePreview()
}, { deep: true })

// 监听预览用量变化
watch(previewUsage, () => {
  calculatePreview()
})

// 生命周期
onMounted(() => {
  loadCustomers()
  loadBillingData()
})
</script>

<style scoped>
.billing-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.query-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 阶梯水费配置样式 */
.tier-config-container {
  padding: 20px 0;
}

.area-info {
  margin-bottom: 20px;
}

.tier-list {
  margin-bottom: 20px;
}

.tier-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.tier-header h4 {
  margin: 0;
  color: #333;
}

.preview-section {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
}

.preview-section h4 {
  margin: 0 0 10px 0;
  color: #333;
}

.preview-amount {
  font-size: 18px;
  font-weight: bold;
  color: #409eff;
}

.preview-form {
  .el-form-item {
    margin-bottom: 10px;
  }
}

/* 表格容器样式 */
.table-container {
  overflow-x: auto;
  margin-bottom: 20px;
}

/* 阶梯配置表格容器 */
.tier-table-container {
  overflow-x: auto;
  margin-bottom: 20px;
}

.tier-table-container .el-table {
  min-width: 800px;
}

/* 预估费用样式 */
.estimated-cost {
  font-weight: bold;
  color: #67c23a;
}

.estimated-cost.zero-cost {
  color: #f56c6c;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .billing-management {
    padding: 15px;
  }
  
  .card-header {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }
}

@media (max-width: 768px) {
  .billing-management {
    padding: 10px;
  }
  
  .query-form {
    .el-form-item {
      margin-bottom: 10px;
    }
  }
  
  .tier-config-container {
    padding: 10px 0;
  }
  
  .tier-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .table-container {
    .el-table {
      font-size: 12px;
    }
    
    .el-table .cell {
      padding: 8px 4px;
    }
  }
  
  .tier-table-container {
    .el-table {
      font-size: 12px;
      min-width: 700px;
    }
    
    .el-table .cell {
      padding: 6px 4px;
    }
    
    .el-input-number {
      width: 100%;
    }
    
    .el-input {
      font-size: 12px;
    }
  }
  
  .preview-form {
    .el-form-item {
      display: block;
      margin-bottom: 8px;
    }
  }
  
  .pagination-container {
    .el-pagination {
      font-size: 12px;
    }
  }
}

@media (max-width: 480px) {
  .billing-management {
    padding: 5px;
  }
  
  .card-header {
    flex-direction: column;
    gap: 8px;
  }
  
  .query-form {
    .el-form-item {
      display: block;
      margin-bottom: 8px;
    }
  }
  
  .tier-table-container {
    .el-table {
      min-width: 600px;
      font-size: 11px;
    }
    
    .el-table .cell {
      padding: 4px 2px;
    }
    
    .el-input-number {
      width: 100%;
    }
    
    .el-input {
      font-size: 11px;
    }
  }
  
  .preview-form {
    .el-form-item {
      display: block;
      margin-bottom: 6px;
    }
    
    .el-input-number {
      width: 100%;
    }
  }
}
</style> 